package com.gvtv.main.email;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.gvtv.main.util.PropertiesHelper;

/**
 * 本程序用java来实现Email的发送， 所用到的协议为：smtp
 */
public class EmailHandle {
	
	private static final Logger logger = Logger.getLogger(EmailHandle.class);

	private MimeMessage mimeMsg; // 邮件对象

	private Session session; // 发送邮件的Session会话

	private Properties props;// 邮件发送时的一些配置信息的一个属性对象

	private String sendUserName; // 发件人的用户名

	private String sendUserPass; // 发件人密码

	private Multipart mp;// 附件添加的组件

	@SuppressWarnings("rawtypes")
	private List files = new LinkedList();// 存放附件文件

	public EmailHandle() {
		this(PropertiesHelper.getString("mail.host"));
		setNamePass(PropertiesHelper.getString("mail.username"), PropertiesHelper.getString("mail.password"));
		setFrom(sendUserName);
	}

	public EmailHandle(String smtp) {
		sendUserName = "";
		sendUserPass = "";
		setSmtpHost(smtp);// 设置邮件服务器
		createMimeMessage(); // 创建邮件
	}

	public void setSmtpHost(String hostName) {
		if (props == null)
			props = System.getProperties();
		props.put("mail.smtp.host", hostName);
		props.put("mail.smtp.auth", PropertiesHelper.getString("mail.smtp.auth","true"));
	}

	public boolean createMimeMessage() {
		try {
			// 用props对象来创建并初始化session对象
			session = Session.getInstance(props, null);
			session.setDebug(PropertiesHelper.getBoolean("mail.debug", false));
		} catch (Exception e) {
			logger.error("获取邮件会话对象时发生错误！" + e.getMessage());
			return false;
		}
		try {
			mimeMsg = new MimeMessage(session); // 用session对象来创建并初始化邮件对象
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	/**
	 * 进行用户身份验证时，设置用户名和密码
	 */
	public void setNamePass(String name, String pass) {
		sendUserName = name;
		sendUserPass = pass;
	}

	/**
	 * 设置邮件主题
	 * 
	 * @param mailSubject
	 * @return
	 */
	public boolean setSubject(String mailSubject) {
		try {
			mimeMsg.setSubject(mailSubject);
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	/**
	 * 设置邮件内容,并设置其为文本格式或HTML文件格式，编码方式为UTF-8
	 * 
	 * @param mailBody
	 * @return
	 */
	public boolean setContent(String content) {
		try {
			if(mp==null){
				mp = new MimeMultipart();// 生成附件组件的实例
			}
			BodyPart bp = new MimeBodyPart();
			bp.setContent(content, "text/html;charset=UTF-8");
			// 在组件上添加邮件文本
			mp.addBodyPart(bp);
		} catch (Exception e) {
			logger.error("设置邮件正文时发生错误！" + e.getMessage());
			return false;
		}
		return true;
	}

	/**
	 * 增加发送附件
	 * 
	 * @param filename
	 *            邮件附件的地址，只能是本机地址而不能是网络地址，否则抛出异常
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public boolean addFileAffix(String filename) {
		try {
			if(mp==null){
				mp = new MimeMultipart();// 生成附件组件的实例
			}
			BodyPart bp = new MimeBodyPart();
			FileDataSource fileds = new FileDataSource(filename);
			bp.setDataHandler(new DataHandler(fileds));
			bp.setFileName(MimeUtility.encodeText(fileds.getName(), "utf-8", null)); // 解决附件名称乱码
			mp.addBodyPart(bp);// 添加附件
			files.add(fileds);
		} catch (Exception e) {
			//System.err.println("增加邮件附件：" + filename + "发生错误！" + e);
			logger.error("增加邮件附件：" + filename + "发生错误！" + e.getMessage());
			return false;
		}
		return true;
	}

	@SuppressWarnings("rawtypes")
	public boolean delFileAffix() {
		try {
			FileDataSource fileds = null;
			for (Iterator it = files.iterator(); it.hasNext();) {
				fileds = (FileDataSource) it.next();
				if (fileds != null && fileds.getFile() != null) {
					fileds.getFile().delete();
				}
			}
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	/**
	 * 设置发件人地址
	 * @param from
	 *            发件人地址
	 * @return
	 */
	public boolean setFrom(String from) {
		try {
			mimeMsg.setFrom(new InternetAddress(from));
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	/**
	 * 设置收件人地址,可以是多个地址,以分好分隔
	 * @param tos收件人的地址
	 * @return
	 */
	public boolean setTo(String tos) {
		if (tos == null||tos.trim().length()<=0)
			return false;
		try {
			String[] arr = StringUtils.split(tos, ";");
			if(arr.length==1){
				mimeMsg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(arr[0]));
			}else {
				InternetAddress[] adds=new InternetAddress[arr.length];
				for(int i=0;i<arr.length;i++){
					adds[i]=new InternetAddress(arr[i]);
		        }
				mimeMsg.addRecipients(Message.RecipientType.TO, adds);
			}
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	/**
	 * 
	 * @param ccs
	 * @return
	 */
	public boolean setCc(String ccs) {
		if (ccs == null||ccs.trim().length()<=0)
			return false;
		try {
			String[] arr = StringUtils.split(ccs, ";");
			if(arr.length==1){
				mimeMsg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(arr[0]));
			}else {
				InternetAddress[] adds=new InternetAddress[arr.length];
				for(int i=0;i<arr.length;i++){
					adds[i]=new InternetAddress(arr[i]);
		        }
				mimeMsg.addRecipients(Message.RecipientType.CC, adds);
			}
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	/**
	 * 发送邮件
	 * 
	 * @return
	 */
	public boolean sendEmail(String subject, String content, String tos, String ccs) {
		setSubject(subject);
		setContent(content);
		setTo(tos);
		setCc(ccs);
		Transport transport = null;
		boolean rel = false;
		// 连接邮件服务器并进行身份验证
		try {
			mimeMsg.setContent(mp);
			transport = session.getTransport("smtp");
			transport.connect((String) props.get("mail.smtp.host"), PropertiesHelper.getInteger("mail.port",25), sendUserName, sendUserPass);
			// 发送邮件
			transport.sendMessage(mimeMsg, mimeMsg.getRecipients(Message.RecipientType.TO));
			rel = true;
			logger.info("发送邮件成功.");
		} catch (Exception e) {
			rel = false;
			e.printStackTrace();
			logger.error("发送邮件失败." + e.getMessage());
		} finally{
			if(transport!=null){
				try {
					transport.close();
				} catch (MessagingException e) {
					e.printStackTrace();
				}
			}
		}
		return rel;
	}
	
	public static void main(String[] args) throws Exception{
		EmailHandle email = new EmailHandle();
		String msg = "<h4 align = \"center\" > demo调度运行情况 </h4> <TABLE align = \"center\" border = \"1\" cellspacing = \"0\" cellpadding = \"2\" width = \"900\" > <tr align = \"center\" > <td> Job ID </td> <td> Job名称 </td> <td> 类型 </td> <td> 状态 </td> <td> 提交时间 </td> <td> 运行时间 </td> <td> 结束时间 </td> </tr> <tr align = \"center\" > <td> aaaaa </td> <td> demodddddddddd </td> <td> MAPREDUCE </td> <td> 运行成功 </td> <td>2015-01-30 12:12:45 </td> <td>2015-01-30 12:14:12</td> <td>2015-01-30 12:18:05</td> </tr> <tr align = \"center\" > <td> aaaaa </td> <td> demodddddddddd </td> <td> MAPREDUCE </td> <td> 运行成功 </td> <td>2015-01-30 12:12:45 </td> <td> 2015-01-30 12:14:12 </td> <td>2015-01-30 12:18:05 </td> </tr> <tr align = \"center\"> <td> aaaaa </td> <td> demodddddddddd </td> <td> MAPREDUCE </td> <td> 运行成功 </td> <td>2015-01-30 12:12:45</td> <td>2015-01-30 12:14:12</td> <td> 2015-01-30 12:18:05</td> </tr> </TABLE>";
		email.sendEmail("邮件测试", msg, "liuwj@gvtv.com.cn", null);
	}
}
